package jjn.round1;

/**
 * @author Jiang Jining
 * @since 2023-06-24 22:54
 */
public class LeetCode37_SudokuServer {
    public void solveSudoku(char[][] board) {
        backtrack(board);
    }
    
    private boolean backtrack(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] != '.') {
                    continue;
                }
                for (char k = '1'; k <= '9'; k++) {
                    if (isValid(i, j, k, board)) {
                        board[i][j] = k;
                        if (backtrack(board)) {
                            return true;
                        }
                        board[i][j] = '.';
                    }
                }
                return false;
            }
        }
        return true;
    }
    
    private boolean isValid(int i, int j, int k, char[][] board) {
        for (int l = 0; l < 9; l++) {
            if (board[i][l] == k) {
                return false;
            }
        }
        for (int l = 0; l < 9; l++) {
            if (board[l][j] == k) {
                return false;
            }
        }
        int startHeight = (i / 3) * 3;
        int startWidth = (j / 3) * 3;
        for (int row = startHeight; row < startHeight + 3; row++) {
            for (int column = startWidth; column < startWidth + 3; column++) {
                if (board[row][column] == k) {
                    return false;
                }
            }
        }
        return true;
    }
}
